package hoyo.zqy.org.service.impl;

import hoyo.zqy.basic.service.impl.BaseServiceImpl;
import hoyo.zqy.basic.util.PageList;
import hoyo.zqy.org.domain.Department;
import hoyo.zqy.org.mapper.DepartmentMapper;
import hoyo.zqy.org.query.DepartmentQuery;
import hoyo.zqy.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public List<Department> deptTree() {
        //将所有的部门撞到map中  - 每次获取父部门都从这里获取
        List<Department> dept = departmentMapper.loadAll();
        Map<Long, Department> map = new HashMap<>();
        for (Department department : dept) {
            map.put(department.getId(),department );
        }
        List<Department> deptTree = new ArrayList<>();
        //遍历所有的部门
        for (Department department : dept) {
            //没有子部门就是顶级父部门
            if (department.getParent_id()==null){
                //添加到部门树
                deptTree.add(department);
            }else {
                //通过id找到父部门
                Long parent_id = department.getParent_id();
                //从map中获取父部门，通过id
                Department parentDepartment = map.get(parent_id);
                if (parentDepartment != null){
                    //把自己封装道父部门
                    parentDepartment.getChildren().add(department);

                }
            }
        }
        return deptTree;
    }

}
